package com.ruoyi.web.controller.common;


import com.bytedance.ads.ApiClient;
import com.bytedance.ads.ApiException;
import com.bytedance.ads.Pair;
import com.bytedance.ads.api.*;
import com.bytedance.ads.model.*;
import com.lark.oapi.Client;
import com.lark.oapi.service.contact.v3.model.FindByDepartmentUserReq;
import com.lark.oapi.service.contact.v3.model.FindByDepartmentUserResp;
import com.lark.oapi.service.contact.v3.model.User;
import com.ruoyi.GetToken;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.framework.config.properties.RedissonProperties;
import com.ruoyi.ocean.domain.bo.OceanAccountBo;
import com.ruoyi.ocean.domain.bo.OceanLogBo;
import com.ruoyi.ocean.domain.vo.OceanAccountVo;
import com.ruoyi.ocean.service.IOceanAccountService;
import com.ruoyi.ocean.service.IOceanLogService;
import com.ruoyi.ocean.service.IOceanUserService;
import com.ruoyi.ocean.service.OpenApiService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.web.controller.OpenEnum.*;
import static com.ruoyi.web.controller.OpenEnum.ZRX_AD_REFRESHTOKEN;

/**
 * @author linziheng
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/openapi")
public class OpenApiController {


    private static final CommonReqApi api = new CommonReqApi();
    private static final Oauth2AdvertiserGetApi advertiserGetApi = new Oauth2AdvertiserGetApi();
    private static final Oauth2RefreshTokenApi refreshTokenApi = new Oauth2RefreshTokenApi();
    private static final ToolsLogSearchV2Api searchV2Api = new ToolsLogSearchV2Api();
    private static final AgentAdvertiserSelectV2Api selectV2Api = new AgentAdvertiserSelectV2Api();
    @Autowired
    private final IOceanAccountService iOceanAccountService;
    @Autowired
    private final IOceanUserService iOceanUserService;
    @Autowired
    private final OpenApiService openApiService;
    private static final ReportAgentGetV2V2Api reportAgentGetV2V2Api = new ReportAgentGetV2V2Api();
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ISysDeptService iSysDeptService;

    @GetMapping("/findByDepartment")
    public final void FindByDepartment() throws Exception {
        // 构建client
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();
        List<SysDept> depts = iSysDeptService.findByDepartment();
        for (SysDept dept : depts) {
            if (dept.getDeptId() != 100L) {
                // 创建请求对象
                FindByDepartmentUserReq req = FindByDepartmentUserReq.newBuilder()
                    .departmentId(dept.getDepartmentId())
                    .build();

                // 发起请求
                FindByDepartmentUserResp resp = client.contact().v3().user().findByDepartment(req);
                for (User item : resp.getData().getItems()) {
                    SysUser user = new SysUser();
                    user.setDeptId(dept.getDeptId());
                    user.setRemark(item.getOpenId());
                    user.setLeaderUserId(item.getLeaderUserId());
                    user.setNickName(item.getName());
                    user.setUserName(item.getMobile().replace("+86", ""));
                    user.setUserType("sys_user");
                    SysUser temp = iSysUserService.selectUserByRemark(item.getOpenId());
                    if (Objects.isNull(temp)) {
                        user.setPassword("$2a$10$L/MJa99w0byDT/b4mnv67uVURzYDSCmk54NkcZmUkmZU/idD8H9by");//123456
                        iSysUserService.insertUser(user);
                    } else {
                        iSysUserService.updateUserOnly(user);
                    }

                }

                // 处理服务端错误
                if (!resp.success()) {
                    System.out.println(String.format("code:%s,msg:%s,reqId:%s"
                        , resp.getCode(), resp.getMsg(), resp.getRequestId()));
                }
            }
        }
    }
    @GetMapping("/reportAgent")
    public R  reportAgent() throws ApiException {
        openApiService.reportAgent();
        return R.ok();
    }
    @GetMapping("/addAccount")
    public R  addAccount() {
        List<Map<String, Object>> list= openApiService.getParams();
        list.forEach(item->{
            try {
                openApiService.addAccount(item);
            } catch (ApiException e) {
                throw new RuntimeException(e);
            }
        });

        return R.ok();
    }
    @GetMapping("/reportAgentBK")
    public R  reportAgentBK() throws ApiException {
        Long agentId = 1775558166641728L;
        Long cursor = null;
        Long cursorSize = null;
        String startDate = "2024-06-01";
        String endDate = "2024-06-02";
        List<Long> advertiserIds = new ArrayList<>();
        advertiserIds.add(1738586828584967L);
        ReportAgentGetV2V2Filtering filtering = new ReportAgentGetV2V2Filtering();
//        ReportAgentGetV2V2Filtering filtering = null;
        filtering.setAdvertiserIds(advertiserIds);
        Long page = null;
        Long pageSize = null;

        ApiClient apiClient = api.getApiClient();
        String access_token = RedisUtils.getCacheObject(HSY_AD_ACCESS_TOKEN);
        apiClient.addDefaultHeader("Access-Token", access_token);
        apiClient.setDebugging(true);
        api.setApiClient(apiClient);
        ReportAgentGetV2V2Response response = reportAgentGetV2V2Api.openApi2ReportAgentGetV2Get(agentId, cursor, cursorSize, endDate, filtering, page, pageSize, startDate);
        System.out.println(response);
        return R.ok();
    }


    public static Map<String, Object> getMap(int type){
        Map<String, Object> requestBody = new HashMap<>();
        switch (type){
            case 1:
                requestBody.put("app_id", ZRX_AD_APP_ID);
                requestBody.put("secret", ZRX_AD_SECRET);
                break;
            case 2:
                requestBody.put("app_id", ZRX_QC_APP_ID);
                requestBody.put("secret", ZRX_QC_SECRET);
                break;
            case 3:
                requestBody.put("app_id", HSY_AD_APP_ID);
                requestBody.put("secret", HSY_AD_SECRET);
                break;
            case 4:
                requestBody.put("app_id", HSY_QC_APP_ID);
                requestBody.put("secret", HSY_QC_SECRET);
                break;
            default:
                System.out.println("??????????????????");
                break;
        }
        requestBody.put("auth_code", "719aecfa0479a5c913241eec0216f49d2e33bcc0");
        return requestBody;

    }
    /**
     * 获取Token
     */
    @GetMapping("/access_token")
    public R  authCode(int type) throws ApiException {
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://api.oceanengine.com");
        apiClient.addDefaultHeader("Access-Token", "test");
        apiClient.setDebugging(true);
        api.setApiClient(apiClient);
        List<Pair> query = new ArrayList<Pair>();
        Map<String, Object> queryParams = new HashMap<>();

        CommonResponse response = api.commonReq("POST", "/open_api/oauth2/access_token/", "application/json", null, null, getMap(type));
        System.out.println(response);

        String accessToken = response.getData().get("access_token").toString();
        String refresh_token = response.getData().get("refresh_token").toString();
        System.out.println(accessToken);
        if(type == 1){
            RedisUtils.setCacheObject(ZRX_AD_ACCESS_TOKEN,accessToken);
            RedisUtils.setCacheObject(ZRX_AD_REFRESHTOKEN,refresh_token);
        }else if(type == 2){
            RedisUtils.setCacheObject(ZRX_QC_ACCESS_TOKEN,accessToken);
            RedisUtils.setCacheObject(ZRX_QC_REFRESHTOKEN,refresh_token);
        }else if(type == 3){
            RedisUtils.setCacheObject(HSY_AD_ACCESS_TOKEN,accessToken);
            RedisUtils.setCacheObject(HSY_AD_REFRESHTOKEN,refresh_token);
        }else if(type == 4){
            RedisUtils.setCacheObject(HSY_QC_ACCESS_TOKEN,accessToken);
            RedisUtils.setCacheObject(HSY_QC_REFRESHTOKEN,refresh_token);
        }

        return R.ok();
    }

    @GetMapping("/refresh_token")
    public R  refreshToken(int type) throws ApiException {

        Oauth2RefreshTokenRequest oauth2RefreshTokenRequest = new Oauth2RefreshTokenRequest();
        oauth2RefreshTokenRequest.setAppId(Long.valueOf(getMap(type).get("app_id").toString()));
        oauth2RefreshTokenRequest.setRefreshToken(RedisUtils.getCacheObject(ZRX_AD_REFRESHTOKEN));
        oauth2RefreshTokenRequest.setSecret(getMap(type).get("secret").toString());
        ApiClient apiClient = refreshTokenApi.getApiClient();
        String access_token = RedisUtils.getCacheObject(ZRX_AD_ACCESS_TOKEN);
        apiClient.addDefaultHeader("Access-Token", access_token);
        apiClient.setDebugging(true);
        refreshTokenApi.setApiClient(apiClient);
        Oauth2RefreshTokenResponse response = refreshTokenApi.openApiOauth2RefreshTokenPost(oauth2RefreshTokenRequest);
        System.out.println(response);
        String accessToken = response.getData().getAccessToken();
        String refreshToken = response.getData().getRefreshToken();
        RedisUtils.setCacheObject(ZRX_AD_ACCESS_TOKEN,accessToken);
        RedisUtils.setCacheObject(ZRX_AD_REFRESHTOKEN,refreshToken);
        return R.ok();
    }


    //获取代理商id
    @GetMapping("/advertiser_get")
    public R  advertiserGet() throws ApiException {

        String accessToken = RedisUtils.getCacheObject(ZRX_AD_ACCESS_TOKEN);
        ApiClient apiClient = advertiserGetApi.getApiClient();
        apiClient.addDefaultHeader("Access-Token", accessToken);
        apiClient.setDebugging(true);
        advertiserGetApi.setApiClient(apiClient);
        Oauth2AdvertiserGetResponse response = advertiserGetApi.openApiOauth2AdvertiserGetGet(accessToken);
        System.out.println(response);

        return R.ok();
    }


    private final IOceanLogService iOceanLogServic;
    @GetMapping("/log_search")
    public R  log_search() throws ApiException {
        List<Long> ssss= new ArrayList<>();
//        List<OceanAccountVo> oceanAccountVoList = iOceanAccountService.queryActiveList();
        OceanAccountBo bo1 = new OceanAccountBo();
        bo1.setAdvertiserId(1779062274167821L);
        List<OceanAccountVo> oceanAccountVoList = iOceanAccountService.queryList(bo1);
        oceanAccountVoList.forEach(oceanAccount->{
            Long page = 1L;
            Long totalNumber = 10L;
            Long cuont = 0L;
            while (cuont< totalNumber){
                String accessToken = "";
                if(oceanAccount.getAgentName().equals("众人行(西安)信息科技有限公司")){
                    if(oceanAccount.getAccountType().equals("AD")){
                        accessToken = RedisUtils.getCacheObject(ZRX_AD_ACCESS_TOKEN);
                    }else{
                        accessToken = RedisUtils.getCacheObject(ZRX_QC_ACCESS_TOKEN);
                    }
                }else{
                    if(oceanAccount.getAccountType().equals("AD")){
                        accessToken = RedisUtils.getCacheObject(HSY_AD_ACCESS_TOKEN);
                    }else{
                        accessToken = RedisUtils.getCacheObject(HSY_QC_ACCESS_TOKEN);
                    }
                }
                String endTime = "2024-06-25 16:59:59";
                List<Long> objectId = null;

                Long pageSize = 100L;
                String startTime = "2024-06-01 00:00:00";
                ApiClient apiClient = searchV2Api.getApiClient();
                apiClient.addDefaultHeader("Access-Token", accessToken);
                apiClient.setDebugging(true);
                searchV2Api.setApiClient(apiClient);
                ToolsLogSearchV2Response response = null;
                try {
                    response = searchV2Api.openApi2ToolsLogSearchGet(oceanAccount.getAdvertiserId(), endTime, objectId, page, pageSize, startTime);


                } catch (ApiException e) {

                }
                if(!Objects.isNull(response) && response.getCode()==0){
                    System.out.println(response.getData().getPageInfo());
                    totalNumber = response.getData().getPageInfo().getTotalNumber();

                    List<ToolsLogSearchV2ResponseDataLogsInner> list = response.getData().getLogs();
                    list.forEach(item->{
                        OceanLogBo bo = new OceanLogBo();

                        //
                        bo.setAccountId(oceanAccount.getAdvertiserId().toString());
                        try {
                            String result = item.getContentLog().stream().collect(Collectors.joining(","));
                            bo.setContentTitle(item.getContentTitle());
                            bo.setContentLog(result);
                        }
                        catch (Exception e) {
                            bo.setContentTitle("信息携带非正常字符");
                            bo.setContentLog("信息携带非正常字符");
                        }

                        String op = item.getOperator();
                        bo.setObjectName(oceanAccount.getAgentName());
                        bo.setOperator(op);
                        bo.setObjectType(oceanAccount.getAccountType());
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            bo.setCreateTime(formatter.parse(item.getCreateTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        //  bo.setObjectId(item.getObjectId().toString());
                        //    bo.setObjectType(item.getObjectType());
                        //    bo.setOptIp(item.getOptIp());
                        try {
                           // iOceanLogServic.insertByBo(bo);
                        }catch (Exception e) {

                        }

                    });
                    page = page +1;
                    cuont = cuont +100;

                }else{
                    cuont= cuont +99999;
                    ssss.add(oceanAccount.getAdvertiserId());

                }

            }
        });

        System.out.println(ssss);
        return R.ok();
    }


//获取代理商下的所有账户
    @GetMapping("/advertiser_select")
    public R  advertiser_select() throws ApiException {
        Long page = null;
        String accessToken = RedisUtils.getCacheObject(ZRX_AD_ACCESS_TOKEN);
        Long advertiserId = 1766673340215303L;
        List<Long> companyIds = null;
        Long count = 2000L;
        Long cursor = 1L;
        AgentAdvertiserSelectV2Filtering filtering = null;
        Long pageSize = null;
        ApiClient apiClient = selectV2Api.getApiClient();
        apiClient.addDefaultHeader("Access-Token", accessToken);
        apiClient.setDebugging(true);
        selectV2Api.setApiClient(apiClient);
        AgentAdvertiserSelectV2Response response = selectV2Api.openApi2AgentAdvertiserSelectGet(advertiserId, companyIds, count, cursor, filtering, page, pageSize);
        System.out.println(response);
        return R.ok();
    }
}
